
const ctx = canvas.getContext('2d')
const window = {
    data: {}
};
export default class Main {
    constructor() {
        // 初始化数据
        this.loadData();
        // 清除画布
        this.clearCanvas();
        canvas.addEventListener('touchstart', this.mousedown);
        canvas.addEventListener('touchmove', this.mousemove);
        canvas.addEventListener('touchend', this.mouseup);
        // 背景音乐
        var bgAudio = new Audio()
        bgAudio.src = 'audio/bg.mp3'
        bgAudio.loop = true;
        wx.onShow(function () {
            bgAudio.play();
        })
    }
    /**
     * 触摸开始
     * @param {*} event 
     */
    mousedown(event) {
        // 触发对象
        if (event.touches) {
            event = event.touches[0];
        }
        // 触摸位置
        var eventX = event.clientX;
        var eventY = event.clientY;
        // 游戏运行中
        if (window.data.isStart) {
            // 鹰
            var eagle = window.data.eagle;
            if (Math.abs(eventX - (eagle.x + eagle.width/2)) < 50 && Math.abs(eventY - (eagle.y + eagle.height/2)) < 50) {
                window.data.eagle.isTouch = true;
                window.data.eagle.touchX = eventX - eagle.x;
                window.data.eagle.touchY = eventY - eagle.y;
            }
        } else { // 游戏未运行
            // 首页
            if (window.data.showIndex) {
                var startButton = window.data.startButton;
                if (Main.prototype.isTouchObj(startButton, eventX, eventY)) {
                    Main.prototype.start();
                } else {
                    // 设置子弹
                    var bulletArea = window.data.bulletArea;
                    for (var i = 0; i < bulletArea.length; i++) {
                        if (Main.prototype.isTouchObj(bulletArea[i], eventX, eventY)) {
                            Main.prototype.setBullet(i);
                            break;
                        }
                    }
                }
            } else { // 游戏结束页面
                var reStartButton = window.data.reStartButton;
                if (Main.prototype.isTouchObj(reStartButton, eventX, eventY)) {
                    window.data.showIndex = true;
                    window.data.gameover = false;
                }
            }
            
        }
        
    }
    /**
     * 鼠标移动/触摸滑动
     * @param {} event 
     */
    mousemove(event) {
        if (window.data.isStart) {
            var eagle = window.data.eagle;
            if (eagle.isTouch) {
                if (event.touches) {
                    event = event.touches[0];
                }
                var eventX = event.clientX;
                var eventY = event.clientY;
                eagle.x = eventX - eagle.touchX;
                eagle.y = eventY - eagle.touchY;
            }
        }
        
    }
    mouseup(event) {
        var eagle = window.data.eagle;
        eagle.isTouch = false;
    }
    /**
     * 发射子弹
     */
    fileBullet() {
        var eagle = window.data.eagle;
        var bulletArr = window.data.bulletArr;
        var bullet = JSON.parse(JSON.stringify(window.data.curBullet));
        bullet.img = window.data.curBullet.img;
        bullet.x = eagle.x + eagle.width/2 - 5;
        bullet.y = eagle.y;
        bulletArr.push(bullet);
        // 发射音乐
        var bulletAudio = new Audio()
        bulletAudio.src = 'audio/bullet.mp3'
        bulletAudio.play();
    }
    bulletMove() {
        var bulletArr = window.data.bulletArr;
        for (var i = 0; i < bulletArr.length; i++) {
          bulletArr[i].y = bulletArr[i].y - 15;
        }
    }
    // 增加羊
    sheepAdd() {
        if (!window.data.isStart) {
            return;
        }
        var sheepArr = window.data.sheepArr;
        var sheep = this.loadSheep();
        sheepArr.push(sheep);
        // 初始每秒3个，每10秒加1个
        var timeout = 1000/(parseInt(window.data.time / 1000 / 10) + 3);
        var that = this;
        setTimeout(function(){
            that.sheepAdd();
        }, timeout);
    }
    sheepMove() {
        var sheepArr = window.data.sheepArr;
        for (var i = 0; i < sheepArr.length; i++) {
          sheepArr[i].y = sheepArr[i].y + sheepArr[i].move;
        }
    }
    drawCanvas() {
        // 首页
        if (window.data.showIndex) {
            this.index();
            return;
        }
        // 游戏中
        if (window.data.isStart) {
            // 处理对象
            this.dealObj();
        }
        // 清除
        this.clearCanvas();
        // 鹰
        ctx.beginPath()
        ctx.fillStyle = "#000";
        var eagle = window.data.eagle;
        var img = eagle.img;
        ctx.drawImage(img, eagle.x, eagle.y, eagle.width, eagle.height);
        ctx.closePath()
        // 子弹
        ctx.beginPath()
        ctx.fillStyle = "#000";
        var bulletArr = window.data.bulletArr;
        for (var i = 0; i < bulletArr.length; i++) {
          var bullet = bulletArr[i];
          var img = bullet.img;
          ctx.drawImage(img, bullet.x, bullet.y, bullet.width, bullet.height);
        }
        ctx.closePath()
        // 羊
        var sheepArr = window.data.sheepArr;
        for (var i = 0; i < sheepArr.length; i++) {
            var sheep = sheepArr[i];
            var img = sheep.img;
            // 羊本体
            ctx.beginPath()
            ctx.drawImage(img, sheep.x, sheep.y, sheep.width, sheep.height);
            ctx.closePath()
            // 血量
            ctx.beginPath()
            ctx.fillStyle = "#000";
            ctx.strokeRect(sheep.x, sheep.y - 10, sheep.width, 10);
            ctx.closePath()
            ctx.beginPath()
            ctx.fillStyle = "#000";
            ctx.fillRect(sheep.x, sheep.y - 10, sheep.width*(sheep.curBlood/sheep.blood), 10);
            ctx.closePath()
        }
        // 时间
        ctx.beginPath()
        ctx.fillStyle = "#000";
        ctx.font = "normal 20px Arial";
        ctx.fillText(window.data.showTime + "秒", canvas.width - 80, 80);
        ctx.closePath();
        // 游戏结束
        if (window.data.gameover) {
             // 操作区域
            ctx.beginPath()
            ctx.fillStyle = 'rgba(255, 255, 255, 0.9)';
            ctx.fillRect(50, 100, canvas.width - 100, canvas.height - 200);
            ctx.closePath();
            // 重新开始按钮
            ctx.beginPath()
            ctx.fillStyle = 'rgba(255, 255, 255, 1)';
            ctx.fillRect(window.data.reStartButton.x, window.data.reStartButton.y, window.data.reStartButton.width, window.data.reStartButton.height);
            ctx.closePath();
            ctx.beginPath()
            ctx.fillStyle = "rgba(0, 0, 0, 1)";
            ctx.strokeRect(window.data.reStartButton.x, window.data.reStartButton.y, window.data.reStartButton.width, window.data.reStartButton.height);
            ctx.closePath();
            ctx.beginPath()
            ctx.fillStyle = "rgba(0, 0, 0, 1)";
            ctx.font = "normal 32px Arial";
            ctx.fillText("回到首页", window.data.reStartButton.x + 15, window.data.reStartButton.y + 36);
            ctx.closePath();
            // 战绩
            // 武器
            var curBullet = window.data.curBullet;
            // 子弹图片
            ctx.beginPath()
            ctx.drawImage(curBullet.img, window.data.reStartButton.x + 15, window.data.reStartButton.y + 65, curBullet.width, curBullet.height);
            ctx.closePath();
            // 子弹文字
            // ctx.beginPath()
            // ctx.fillStyle = "rgba(0, 0, 0, 1)";
            // ctx.font = "normal 16px Arial";
            // ctx.fillText(curBullet.name, window.data.reStartButton.x + 50, window.data.reStartButton.y + 80);
            // ctx.closePath();
            // 持续时间
            ctx.beginPath()
            ctx.fillStyle = "rgba(0, 0, 0, 1)";
            ctx.font = "normal 20px Arial";
            ctx.fillText(window.data.showTime + "秒", window.data.reStartButton.x + 50, window.data.reStartButton.y + 83);
            ctx.closePath();
            // 杀死羊
            var i = 0;
            for (var type in window.data.killSheep) {
                var text = type + "：" + window.data.killSheep[type] + "个";
                ctx.beginPath()
                ctx.fillStyle = "rgba(0, 0, 0, 1)";
                ctx.font = "normal 20px Arial";
                ctx.fillText(text, window.data.reStartButton.x, window.data.reStartButton.y + 120 + 35 * i++);
                ctx.closePath();
            }
        }i++
    }
    dealObj() {
        var canvas = window.data.canvas;
        // 移除屏幕外子弹
        var bulletArr = window.data.bulletArr;
        for (var i = 0; i < bulletArr.length; i++) {
          var bullet = bulletArr[i];
          if (bullet.y < 0) {
            bulletArr.splice(i, 1);
            i--;
          }
        }
        // 移除屏幕外羊
        var sheepArr = window.data.sheepArr;
        for (var i = 0; i < sheepArr.length; i++) {
          var sheep = sheepArr[i];
          if (sheep.y > canvas.height) {
            sheepArr.splice(i, 1);
            i--;
          }
        }
        // 子弹碰上羊
        for (var i = 0; i < bulletArr.length; i++) {
            var bullet = bulletArr[i];
            var hit = false;
            for (var j = 0; j < sheepArr.length; j++) {
                var sheep = sheepArr[j];
                if (this.isBump(sheep, bullet)) {
                    sheep.curBlood = sheep.curBlood - bullet.harm;
                    if (sheep.curBlood <= 0) {
                        // 羊消失音乐
                        var boomAudio = new Audio()
                        boomAudio.src = 'audio/boom.mp3'
                        boomAudio.play();
                        if (!window.data.killSheep[sheep.type]) {
                            window.data.killSheep[sheep.type] = 0;
                        }
                        window.data.killSheep[sheep.type]++;
                        sheepArr.splice(j, 1);
                        j--;
                    }
                    hit = true;
                    break;
                }
            }
            if (hit) {
                bulletArr.splice(i, 1);
                i--;
            }
        }
        // 鹰碰上羊
        var eagle = window.data.eagle;
        for (var i = 0; i < sheepArr.length; i++) {
          var sheep = sheepArr[i];
          if (this.isBump(sheep, eagle, 70, 20)) {
            this.gameover();
            return;
          }
        }
    }
    gameover() {
        window.data.isStart = false;
        window.data.gameover = true;
        // 清除定时
        var IntervalArr = window.data.IntervalArr;
        for (var i = 0; i < IntervalArr.length; i++) {
            clearInterval(IntervalArr[i]);
        }
        var that = this;
        // setTimeout(function(){
        //     that.gameover();
        // }, 1000);
    }
    /**
     * 游戏开始
     */
    start() {
        window.data.killSheep = {};
        window.data.showIndex = false;
        var eagle = window.data.eagle;
        var bulletArr = window.data.bulletArr;
        var sheepArr = window.data.sheepArr;
        /**
         * 鹰
         */
        eagle = this.loadEagle();
        /**
         * 子弹
         */
        bulletArr = [];
        /**
         * 羊
         */
        sheepArr = [];
        window.data.eagle = eagle;
        window.data.bulletArr = bulletArr;
        window.data.sheepArr = sheepArr;
        // 时间
        window.data.time = 0;
        // 开始
        window.data.isStart = true;
        // 加载定时
        this.loadInterval();
        // 开始增加羊
        this.sheepAdd();
    }
    // 初始化鹰
    loadEagle() {
        var img = new Image();
        img.src = "img/eagle.png";
        return {
            width: 80,
            height: 50,
            x: canvas.width/2 - 50,
            y: canvas.height - 200,
            touchX: 0,
            touchY: 0,
            isTouch: false,
            img: img
        };
    }
    // 初始化羊
    loadSheep() {
        // 羊类型
        var type = "";
        var x = (canvas.width - 70) * Math.random();
        var y = 0;
        var width = 70;
        var height = 70;
        // 血量
        var blood = 100; 
        // 初始速度2，每10秒速度+1
        var move = 2 + (parseInt(window.data.time/1000/20) * 1);
        var img = new Image();
        var random = Math.random();
        if (random < 0.07) {
            // 7% alpha
            img.src = "img/alpha.png";
            blood = 300;
            type = "Alpha";
        } else if (random >= 0.07 && random < 0.12) {
            // 5% beta
            img.src = "img/beta.png";
            blood = 200;
            type = "Beta";
        } else if (random >= 0.12 && random < 0.17) {
            // 5% gamma
            img.src = "img/gamma.png";
            blood = 200;
            type = "Gamma";
        } else if (random >= 0.17 && random < 0.2) {
            // 3% delta
            img.src = "img/delta.png";
            blood = 400;
            type = "Delta";
        } else {
            // 80% omicron
            img.src = "img/omicron.png";
            blood = 100;
            type = "Omicron";
        }
        // 剩余血量
        var curBlood = blood;
        return {
            x: x,
            y: y,
            width: width,
            height: height,
            move: move, // 羊的速度
            blood: blood,
            curBlood: curBlood,
            img: img,
            type: type
        }
    }
    // 物体碰撞
    isBump(obj1, obj2, defaultDistanceX, defaultDistanceY) {
        var distanceX = obj1.width/2 + obj2.width/2;
        var distanceY = obj1.height/2 + obj2.height/2;
        if (defaultDistanceX && defaultDistanceY) {
            distanceX = defaultDistanceX;
            distanceY = defaultDistanceY;
        }
        return (Math.abs(obj1.x + obj1.width/2 - (obj2.x + obj2.width/2)) < distanceX) && (Math.abs(obj1.y + obj1.height/2 - (obj2.y + obj2.height/2)) < distanceY);
    }
    /**
     * 加载首页
     */
    index() {
        this.clearCanvas();
        window.data.IntervalArr = [];
        // 操作区域
        ctx.beginPath()
        ctx.fillStyle = 'rgba(255, 255, 255, 0.5)';
        ctx.fillRect(50, 100, canvas.width - 100, canvas.height - 200);
        ctx.closePath();
        // 开始按钮
        ctx.beginPath()
        ctx.fillStyle = "#fff";
        ctx.fillRect(window.data.startButton.x, window.data.startButton.y, window.data.startButton.width, window.data.startButton.height);
        ctx.closePath();
        ctx.beginPath()
        ctx.fillStyle = "rgba(0, 0, 0, 1)";
        ctx.font = "normal 32px Arial";
        ctx.fillText("开始", window.data.startButton.x + 15, window.data.startButton.y + 36);
        ctx.closePath();
        // 选择子弹
        ctx.beginPath()
        ctx.fillStyle = "rgba(0, 0, 0, 1)";
        ctx.font = "normal 16px Arial";
        ctx.fillText("选择子弹：", 80, 230);
        ctx.closePath();
        window.data.bulletArea = [];
        if (!window.data.curBullet) {
            window.data.curBullet = window.data.bulletType[0];
        }
        for (var i = 0; i < window.data.bulletType.length; i++) {
            var bulletItem = window.data.bulletType[i];
            this.drawBullet(bulletItem, i);
        }
    }
    /**
     * 清除画布
     */
    clearCanvas() {
        // 背景
        ctx.beginPath()
        ctx.fillStyle = "#87CEEB";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        // var img = new Image();
        // img.src = "img/bg.png";
        // ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        ctx.closePath();
    }
    /**
     * 初始化数据
     */
    loadData() {
        window.data = {
            // 鹰
            eagle: {},
            // 子弹
            bulletArr: [],
            // 羊
            sheepArr: [],
            // 开始
            isStart: false,
            // 结束
            gameover: false,
            // 画布
            canvas: {},
            // 首页
            showIndex: true,
            // 发射子弹定时
            fileBulletInterval: null,
            // 子弹移动定时
            bulletMoveInterval: null,
            // 每秒3个羊定时
            sheepAddInterval: null,
            // 羊移动定时
            sheepMoveInterval: null,
            // 时间
            time: 0,
            // 时间显示
            showTime: '',
            // 开始按钮
            startButton: {
                width: 100,
                height: 50,
                x: canvas.width/2 - 50,
                y: 150
            },
            // 重新开始按钮
            reStartButton: {
                width: 160,
                height: 50,
                x: canvas.width/2 - 80,
                y: 150
            },
            // 所有定时
            IntervalArr: [],
            // 所有子弹
            bulletType: [
                {
                    name: '黄桃罐头',
                    // img: 'img/bullet-taozi.png',
                    width: 20,
                    height: 20,
                    harm: 50
                },
                {
                    name: '连花清瘟胶囊',
                    // img: 'img/bullet-lhqw.png',
                    width: 20,
                    height: 20,
                    harm: 100
                },
                {
                    name: '对乙酰氨基酚',
                    // img: 'img/bullet-对乙酰氨基酚.png',
                    width: 20,
                    height: 20,
                    harm: 150
                },
                {
                    name: 'n95',
                    // img: 'img/bullet-n95.png',
                    width: 20,
                    height: 20,
                    harm: 80
                }
            ],
            // 当前子弹
            curBullet: null,
            // 子弹选择区域
            bulletArea: [],
            // 战绩
            killSheep: {}
        }
        var img0 = new Image();
        img0.src = "img/bullet-taozi.png"
        window.data.bulletType[0].img = img0;
        var img1 = new Image();
        img1.src = "img/bullet-lhqw.png"
        window.data.bulletType[1].img = img1;
        var img2 = new Image();
        img2.src = "img/bullet-对乙酰氨基酚.png"
        window.data.bulletType[2].img = img2;
        var img3 = new Image();
        img3.src = "img/bullet-n95.png"
        window.data.bulletType[3].img = img3;
        var that = this;
        // setInterval(function(){
        //     if (window.data.showIndex) {
        //         that.index();
        //     }
        // }, 1000);
        // 绘制
        setInterval(function(){
            that.drawCanvas()
        }, 1000/60);
        // window.data.IntervalArr.push(drawInterval);
    }
    /**
     * 加载定时
     */
    loadInterval() {
        // 定时任务
        var that = this;
        // 每秒4发子弹
        window.data.fileBulletInterval = setInterval(function(){
            that.fileBullet()
        }, 1000/4);
        window.data.IntervalArr.push(window.data.fileBulletInterval);
        // 子弹移动
        window.data.bulletMoveInterval = setInterval(function(){
            that.bulletMove()
        }, 1000/30);
        window.data.IntervalArr.push(window.data.bulletMoveInterval);
        // 羊移动
        window.data.sheepMoveInterval = setInterval(function(){
            that.sheepMove()
        }, 1000/100);
        window.data.IntervalArr.push(window.data.sheepMoveInterval);
        // // 每秒3个羊
        // window.data.sheepAddInterval = setInterval(function(){
        //     that.sheepAdd()
        // }, 1000/3);
        // window.data.IntervalArr.push(window.data.sheepAddInterval);
        // // 每10秒，每秒增加1个羊
        // window.data.sheepAddIntervalNum = setInterval(function(){
        //     var sheepAddIntervalItem = setInterval(function(){
        //         that.sheepAdd()
        //     }, 1000/1);
        //     window.data.IntervalArr.push(sheepAddIntervalItem);
        // }, 10000);
        // window.data.IntervalArr.push(window.data.sheepAddIntervalNum);
        var setTimeInterval = setInterval(function(){
            that.setTime()
        }, 1000/10);
        window.data.IntervalArr.push(setTimeInterval);
    }
    /**
     * 是否选中对象
     * @param {对象} obj 
     * @param {触摸x坐标} eventX 
     * @param {触摸y坐标} eventY 
     */
    isTouchObj(obj, eventX, eventY) {
        return (eventX - obj.x < obj.width && eventY - obj.y < obj.height);
    }
    /**
     * 设置时间
     */
    setTime() {
        var time = window.data.time + 1000/10;
        var showTime = (time/1000).toString();
        if (showTime.indexOf(".") > -1) {
            showTime = showTime.substr(0, showTime.indexOf(".") + 4);
        }
        window.data.time = time;
        window.data.showTime = showTime;
    }
    /**
     * 画子弹
     * @param {子弹类型} bulletItem 
     */
    drawBullet(bulletItem, i) {
        var img = bulletItem.img
        // img.onload = function() {
            // 区域
            ctx.beginPath()
            ctx.fillStyle = 'rgba(255, 255, 255, 0.5)';
            if (window.data.curBullet.name == bulletItem.name) {
                ctx.fillStyle = 'rgba(255, 255, 255, 1)';
            }
            var area = {
                x: 70,
                y: 246 + (i * 30),
                width: canvas.width - 140,
                height: 28
            };
            ctx.fillRect(area.x, area.y, area.width, area.height);
            window.data.bulletArea.push(area);
            ctx.closePath();
            // 子弹图片
            ctx.beginPath()
            ctx.drawImage(img, 80, 250 + (i * 30), bulletItem.width, bulletItem.height);
            ctx.closePath();
            // 子弹文字
            ctx.beginPath()
            ctx.fillStyle = "rgba(0, 0, 0, 1)";
            ctx.font = "normal 16px Arial";
            ctx.fillText(bulletItem.name, 108, 268 + (i * 30));
            ctx.closePath();
        // }
    }
    /**
     * 设置子弹
     * @param {*} i 
     */
    setBullet(i) {
        window.data.curBullet = window.data.bulletType[i];
        // 重绘
        this.clearCanvas();
    }
}